package com.kangjia.http;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class HttpRequest {

	@Autowired
	private OkHttpClient okHttpClient;

	/**
	 * post json 请求
	 * 
	 * @param url
	 * @param json
	 * @return
	 */
	public HttpResponse json(String url, String json) {
		log.info("post json 请求url={}, json={}", url, json);
		RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
		Request request = new Request.Builder().url(url).post(requestBody).build();
		return handler(request);
	}

	/**
	 * get 请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public HttpResponse get(String url, List<HttpParam> params) {
		log.info("get 请求url={}, json={}", url, params);
		StringBuilder str = new StringBuilder();
		for (HttpParam param : params) {
			str.append("&");
			str.append(param.getParam());
			str.append("=");
			str.append(param.getValue());
		}
		url = url + str.replace(0, 1, "?");
		Request request = new Request.Builder().url(url).get().build();
		return handler(request);
	}

	/**
	 * form 请求
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	public HttpResponse form(String url, List<HttpParam> params) {
		log.info("post form 请求url={}, json={}", url, params);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		for (HttpParam param : params) {
			builder.add(param.getParam(), param.getValue());
		}
		RequestBody formBody = builder.build();
		Request request = new Request.Builder().url(url).post(formBody).build();
		return handler(request);
	}

	/**
	 * 返回结果处理
	 * 
	 * @param request
	 * @return
	 */
	private HttpResponse handler(Request request) {
		Response response;
		try {
			response = okHttpClient.newCall(request).execute();
		} catch (IOException e) {
			return new HttpResponse(90001, e.getMessage());
		}
		try {
			ResponseBody rp = response.body();
			if (response.isSuccessful()) {
				return new HttpResponse(response.code(), rp.string());
			} else {
				return new HttpResponse(response.code(), rp.string());
			}
		} catch (IOException e) {
			return new HttpResponse(90002, e.getMessage());
		}
	}
}
